<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\exception\ValidateException;
use service\JsonService as Json;
use think\facade\{View, Session};

use app\common\model\{User, Star};
use app\common\validate\{UserValidate};

class UserController extends BaseController
{
    /**
     * 渲染用户列表页面
     */
    public function user_list()
    {   
        View::assign('token', Session::get('token'));
        return view();
    }

    /**
     * 渲染用户编辑页面
     */
    public function user_edit()
    {   
        $data = input('');

        $info = User::getFind(['id' => $data['id']]);
        $star_list = Star::getList([], 0);

        View::assign('info', $info);
        View::assign('star_list', $star_list);
        return view();
    }

    /**
     * 获取用户列表数据
     */
    public function user_data()
    {   
        $data = input('');

        try{
            validate(UserValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where = [];

        if($data && isset($data['key'])){
            if(!empty($data['key']['nickname'])){
                $where[] = ['nickname', 'like', '%' . $data['key']['nickname'] . '%'];
            }

            if(!empty($data['key']['mobile'])){
                $where[] = ['mobile', 'like', '%' . $data['key']['mobile'] . '%'];
            }
        }
        
        $field = 'id, pid, nickname, avatar, mobile, star, money, money_brokerage, money_red, point, status, create_time';
        $list = User::getList($where, 1, $data['page'], $data['limit'], $field);

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list, User::getNum($where));
    }

    /**
     * 用户的启用||禁用
     */
    public function setStatus()
    {
        $data = input('');
        $status = User::setStatus($data['id']);
        return Json::success($status['msg']);
    }

    /**
     * 用户信息修改
     */
    public function user_edit_data()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }
        
        $flag = User::edit($data);

        if($flag === false) return Json::fail('修改失败');
        return Json::success('修改成功');
    }

    /**
     * 删除管理员
     */
    public function user_del()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $flag = User::destroy($data['id']);

        if(!$flag) return Json::fail('删除失败');
        return Json::success('删除成功');
    }
}
